import React, { useState, useEffect } from "react";
import {
  Button,
  Modal,
  Cascader,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Radio,
  Select,
  Switch,
  TreeSelect,
  Space,
  Tag,
  Table,
  Popconfirm,
  Row,
  Col,
} from "antd";
import dayjs from "dayjs";
import moment from "moment";
import config from "../dictionary";
import "moment/locale/zh-cn";
import locale from "antd/es/date-picker/locale/zh_CN";
import {
  accountAdd,
  accountQuery,
  accountDel,
  accountUpdate,
} from "../services/accountService";

export default function Account() {
  const [isModalOpen, setIsModalOpen] = useState(false); //控制是否显示
  const [form] = Form.useForm();
  const [editId, setEditId] = useState(0);
  const [year, setyear] = useState(""); //年
  const [month, setmonth] = useState(""); //月
  const [type2, settype2] = useState("");//类别

  const columns = [
    {
      title: "日期",
      dataIndex: "date",
      key: "date",
    },
    {
      title: "金额",
      dataIndex: "money",
      render: (_, item) => {
        return (
          <button>
            {item.type ? "+" : "-"}
            {item.money}
          </button>
        );
      },
    },
    {
      title: "分类",
      dataIndex: "type2",
      render: (_, item) => {
        return (
          <>
            <span>{config[item.type2]}</span>
          </>
        );
      },
    },
    {
      title: "备注",
      dataIndex: "remark",
      key: "remark",
    },
    {
      title: "操作",
      render: (_, item) => (
        <>
          <Button
            onClick={() => {
              showEditDialog(item);
            }}
          >
            编辑
          </Button>
          <Popconfirm title="删除记录" onConfirm={() => onDelete(item.id)}>
            <Button>删除</Button>
          </Popconfirm>
        </>
      ),
    },
  ];
  const [data, setdata] = useState([]); //data是集合

  let onDelete = async (id) => {
    //删除
    await accountDel(id);
    setdata(data.filter((item) => item.id !== id));
  };

  let search = async () => {
    let params = {};
    if (year) {
      params.year = year;
      params.month = month;
    }
    if(type2){
      params.type2 = type2;
    }
    //查询的方法
    let res = await accountQuery(params);
    setdata(res.data);
  };

  useEffect(() => {
    search();
    return () => {};
  }, []);

  const showModal = () => {
    setIsModalOpen(true);
  };
  const showEditDialog = (item) => {
    //编辑的对象
    setIsModalOpen(true);
    setEditId(item.id);
    form.setFieldsValue({
      ...item,
      date: moment(item.date),
      type: item.type ? true : false,
    });
  };
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    form.resetFields();
    setIsModalOpen(false);
    setEditId(0);
  };
  const onFinish = async (values) => {
    let date = dayjs(values.date).format("YYYY-MM-DD");
    let type = values.type == true ? 1 : 0;
    let year = dayjs(values.date).format("YYYY");
    let month = dayjs(values.date).format("MM");
    if (editId) {
      await accountUpdate(editId, {
        ...values,
        date,
        type,
        year,
        month,
      });
      //更新集合
      setdata(
        data.map((item) => {
          if (item.id === editId) {
            item = { ...item, ...values, date, type, year, month };
          }
          return item;
        })
      );

      handleCancel(); //关闭
      return false;
    }
    let res = await accountAdd({
      ...values,
      date,
      type,
      year,
      month,
    });
    setdata([...data, res.data]);
    handleCancel(); //关闭
  };
  const onFinishFailed = (errorInfo) => {
    console.log("Failed:", errorInfo);
  };

  const onReset = () => {
    //清空事件
    handleCancel();
  };
  const onChange = (date, dateString) => {
    //日期的改变事件
    // console.log(date, dateString);
    if (date) {
      let month  = dayjs(date).format("MM");
      // console.log(month);
      //有时间就设置年月
      let newDate = date._d; //这才是真的时间
      setyear(newDate.getFullYear());
      setmonth(month);
    } else {
      //没有就清空
      setyear("");
      setmonth("");
    }
  };
  const handleChange = (value) => {
    //类别的改变事件
    settype2(value);
  };
  return (
    <div>
      <Row gutter={16}>
        <Col className="gutter-row" span={8}>
          <div>
            <DatePicker locale={locale} onChange={onChange} picker="month" />
          </div>
        </Col>
        <Col className="gutter-row" span={8}>
          <div>
            <Select
              defaultValue=""
              style={{
                width: 120,
              }}
              onChange={handleChange}
              options={[{ value: "", label: "全部" }].concat(
                Object.keys(config).map((key) => ({
                  value: key,
                  label: config[key],
                }))
              )}
            />
          </div>
        </Col>
        <Col className="gutter-row" span={8}>
          <div>
            {" "}
            <Button type="primary" onClick={search}>
              查询
            </Button>
            <Button>取消</Button>
          </div>
        </Col>
      </Row>
      <Row>
        <Col sm={24} md={24} lg={8}>
          Col
        </Col>
        <Col sm={24} md={24} lg={8}>
          Col
        </Col>
        <Col sm={24} md={24} lg={8}>
          Col
        </Col>
      </Row>
      <div>
        <Button type="primary" onClick={showModal}>
          记一笔
        </Button>
      </div>
      <Modal
        title="新增数据"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <Form
          labelCol={{
            span: 4,
          }}
          wrapperCol={{
            span: 14,
          }}
          form={form}
          layout="horizontal"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Form.Item
            label="金额"
            name="money"
            rules={[
              {
                required: true,
                message: "金额不能为空",
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="日期"
            name="date"
            rules={[
              {
                required: true,
                message: "日期不能为空",
              },
            ]}
          >
            <DatePicker locale={locale} />
          </Form.Item>

          <Form.Item label="类型" valuePropName="checked" name="type">
            <Switch checkedChildren="收入" unCheckedChildren="支出" />
          </Form.Item>

          <Form.Item
            label="分类"
            name="type2"
            rules={[
              {
                required: true,
                message: "最少选择一个",
              },
            ]}
          >
            <Radio.Group>
              <Radio value="1">早餐</Radio>
              <Radio value="2">电子</Radio>
              <br />
              <Radio value="3">工资</Radio>
              <Radio value="4">衣物</Radio>
              <br />
              <Radio value="5">理财</Radio>
              <Radio value="6">其他</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="备注" name="remark">
            <Input.TextArea showCount maxLength={100} />
          </Form.Item>

          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            <Button htmlType="button" onClick={onReset}>
              取消
            </Button>
          </Form.Item>
        </Form>
      </Modal>

      <Table columns={columns} dataSource={data} rowKey="id" />
    </div>
  );
}
